package com.greateamd.timetableasy.client.mvc.view.crud.planning;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Widget;
import com.greateamd.timetableasy.client.mvc.model.PlanningModel;
import com.greateamd.timetableasy.client.mvc.view.TimeTableasyPage;
import com.greateamd.timetableasy.client.services.cursus.CursusService;
import com.greateamd.timetableasy.client.services.cursus.CursusServiceAsync;
import com.greateamd.timetableasy.client.services.util.ServerCall;
import com.greateamd.timetableasy.client.widgets.ClassicLargeLabel;
import com.greateamd.timetableasy.client.widgets.EntityContainer;
import com.greateamd.timetableasy.client.widgets.cursus.CursusListBox;
import com.greateamd.timetableasy.domain.Event;
import com.greateamd.timetableasy.domain.StudyPeriod;

public class StudyPeriodPlanningPage <M extends PlanningModel> extends PlanningPage<M> {
	
	private final CursusListBox listOfCursusAvailable;
	private final EntityContainer<StudyPeriod> listOfSp;
	
	public StudyPeriodPlanningPage(M model) {
		super(model);
		listOfSp = new EntityContainer<StudyPeriod>(false);
		listOfSp.setTitle(".. and select a Study Period");
		listOfCursusAvailable = new CursusListBox(true,false);
		listOfCursusAvailable.setTitle("All cursus found, select one..");
		listOfCursusAvailable.addChangeHandler(new ChangeHandler() {
			@Override
			public void onChange(ChangeEvent arg0) {
				if(listOfCursusAvailable.getSelectedCursus() != null){
					listOfSp.clear();
					for(StudyPeriod sp : listOfCursusAvailable.getSelectedCursus().getStudyPeriods()){
						listOfSp.addEntity(sp);
					}
				}
			}
		});
		
		final FlowPanel panel = new FlowPanel();
		panel.add(new ClassicLargeLabel("Choose desired study period"));
		panel.add(listOfCursusAvailable);
		panel.add(listOfSp);
		setExtraPanel(panel);
	}
	
	//---------------------------------------------------------------------
	//-------------------------- Server call
	
	@Override
	protected void callServerEvent() {
		new ServerCall<List<Event>>() {

			@Override
			protected void callService(AsyncCallback<List<Event>> asyncCallback) {
				final CursusServiceAsync cursusService = GWT.create(CursusService.class);
				cursusService.getStudyPeriodPlanning(listOfSp.getSelectedEntity(),getFromDate(),getToDate(),asyncCallback);
			}

			@Override
			public void onSuccess(List<Event> result) {
				model.setEvents(result);
				refreshPlanning(TimeTableasyPage.PLANNING_STUDYPERIOD);
			}
		}.call();
	}

	@Override
	protected Widget getWidgetPage() {
		return this;
	}
}
